# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging
import json

from pylons import tmpl_context as c, request, url
from pylons.controllers.util import redirect

from sqlalchemy import func

from chowa.lib.base import BaseController, render, Session
from chowa.model.navigation import HomepageBlock

log = logging.getLogger(__name__)

# TODO: move to the lib
def _get_block(row, col):
    query = Session.query(HomepageBlock)
    try:
        block = query.filter_by(row=row).filter_by(col=col).one()
    except:
        blocks = query.all()
        blocking = []
        for block in blocks:
            for row_shift in range(block.rowspan):
                for col_shift in range(block.colspan):
                    _row = block.row + row_shift
                    _col = block.col + col_shift
                    while (_row, _col) in blocking: _row += 1
                    blocking += [(_row, _col)]
        if (row, col) in blocking:
            return None
        return 'empty'
    
    tokens = block.component.split('.')
    module_name = tokens[-2].__str__()
    components = __import__('.'.join(tokens[0:-2]), fromlist=[module_name])
    module = components.__dict__[tokens[-2]]
    
    options = {}
    try:
        options = json.loads(block.options)
    except Exception:
        pass
    
    # load the component's class
    component = getattr(module, tokens[-1])(options)
    block.render = component.render
    return block

class HomepageController(BaseController):
    __primary_tabs__ = []
    
    __secondary_tabs__ = []
    
    def index(self):
        identity = request.environ.get('repoze.who.identity')
        if identity:
            user = identity.get('user')
            if user.bad_password:
                return redirect(url(controller='social/profile', action='password'))
        try:
            c.rows = Session.query(func.max(HomepageBlock.row)).one()[0] + 1
            c.cols = Session.query(func.max(HomepageBlock.col)).one()[0] + 1
        except:
            c.rows = 0
            c.cols = 0
        c.block = _get_block
        
        return render('/site/index.html', extra_vars={'is_homepage': True})

